<?php
/*
 * @Author: 代勇 1031850847@qq.com
 * @Date: 2023-11-06 08:53:01
 * @LastEditors: 代勇 1031850847@qq.com
 * @LastEditTime: 2024-03-27 09:29:57
 * @Description: 图片上传
 */

namespace Controller\Uploads;

use Intervention\Image\ImageManagerStatic as ImageMake;
use Daiyong\File as file;
use Daiyong\Func as func;

class Image extends \Controller\Common {
    private $savePath = 'www/data/images/'; //保存的目录
    private $httpPath = 'data/images/'; //站点访问根目录
    public function index() {
        $file = current($_FILES);
        //判断图片格式
        $ext = explode('.', $file['name']);
        $ext = strtolower($ext[count($ext) - 1]);
        if (!in_array($ext, $this->config['upload']['image']['ext'])) {
            $this->error('"' . $file['name'] . '" 格式错误,请上传(' . implode(',', $this->config['upload']['image']['ext']) . ')格式的图片');
        }
        //判断图片大小
        if ($file['size'] > $this->config['upload']['image']['maxSize']) {
            $maxSize = number_format($this->config['upload']['image']['maxSize'] / 1024 / 1024, 2) * 100 / 100;
            $nowSize = number_format($file['size'] / 1024 / 1024, 2) * 100 / 100;
            $this->error('"' . $file['name'] . '" 文件大小为' . $nowSize . 'M, 超过了' . $maxSize . 'M的上传限制。');
        }
        //设置图片存储信息
        $fileName = date('Ymd') . '/' . date('YmdHis') . '_' . func::random(5) . '.' . $ext;
        $path = file::path($this->savePath . $fileName, true);
        //判断图片尺寸
        list($width, $height) = getimagesize($file['tmp_name']);
        if ($width <= $this->config['upload']['image']['maxWidth']) { //宽度小于允许的宽度直接保存
            move_uploaded_file($file['tmp_name'], $path);
        } else { //宽度大于允许的宽度
            if ($width * $height > 3000 * 4000 * 1.2) { //如果图片太大可能超出处理内存
                $this->error('"' . $file['name'] . '" 长宽为' . $width . ' x ' . $height . ', 请压缩在一个合理的范围内后上传');
            }
            $img = ImageMake::make($file['tmp_name']);
            $img->resize($this->config['upload']['image']['maxWidth'], (int)($this->config['upload']['image']['maxWidth'] / $img->width() * $img->height()));
            $img->save($path, 100);
        }
        //获取网络路径
        $http = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'];
        $http_plus = dirname(parse_url($_SERVER['SCRIPT_NAME'])['path']) . '/';
        if ($http_plus == '\\/') $http_plus = '/';
        $http = $http . $http_plus;

        $this->success(array(
            'name' => $file['name'],
            'url' => $http . $this->httpPath . $fileName,
        ), '上传成功');
    }
}
